package com.gscitysfy.cus.drain.utils;

import org.springframework.context.ConfigurableApplicationContext;

/**
 * Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean
 *
 * @author fengshuonan
 * @date 2016年11月27日 下午3:32:11
 */

public class SpringContextHolder {
    private static ConfigurableApplicationContext context = null;

    private SpringContextHolder() { }

    public static void setContext(ConfigurableApplicationContext context){
        com.gscitysfy.cus.drain.utils.SpringContextHolder.context = context;
    }

    public static ConfigurableApplicationContext getInstance() {
        if(null==context){
            throw new RuntimeException("SpringContextHolder 尚未初始化");
        }
        return context;
    }

    public static <T> T getBean(String className) {
        if(null==context){
            throw new RuntimeException("SpringContextHolder 尚未初始化");
        }
        return (T)context.getBean(className);
    }

    public static <T> T getBean(Class<T> classType) {
        if(null==context){
            throw new RuntimeException("SpringContextHolder 尚未初始化");
        }
        return context.getBean(classType);
    }
}
